package io.iec.edp.caf.rest.client.tests;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.multicontext.annotation.BeanCollector;
import io.iec.edp.caf.rest.RESTEndpoint;
import io.iec.edp.caf.rest.RESTServiceRegistrar;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Configuration
@Slf4j
public class Config {
    @Bean
    TestServiceApi createTestApi(){
        return new TestServiceApilmpl();
    }

    @Bean
    public RESTEndpoint myTestApiRestEndPoint(TestServiceApi rest ){
        return new RESTEndpoint("/Test",rest);
    }

    @Bean
    @BeanCollector
    @ConditionalOnBean(RESTEndpoint.class)
    @ConditionalOnMissingBean(name = "defaultRestServer")
    public List<Server> defaultRestServer(
            Bus bus,
            List<RESTEndpoint> endpoints,
            ApplicationContext context
    ) throws InterruptedException {
        SpringBeanUtils.setApplicationContext(context);

        RESTServiceRegistrar restServiceRegistrar = RESTServiceRegistrar.getSingleton();
        restServiceRegistrar.finishRegistry();
        List<RESTEndpoint> endpointsCopy = new ArrayList<>(endpoints);
        endpoints.addAll(restServiceRegistrar.getEndpoints());
        restServiceRegistrar.putEndpoints(endpointsCopy);
        ExecutorService logThread = new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        logThread.execute(()->{
            CountDownLatch countDownLatch = new CountDownLatch(endpoints.size());

            ExecutorService executor = new ThreadPoolExecutor(64, 64,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>());
            for (RESTEndpoint endpoint : endpoints) {
                executor.execute(() -> {
//                RESTEndpointUtil.createJAXRSServer(endpoint.getPath(), bus, endpoint.getServices());
                    restServiceRegistrar.publishRestEndpoint(endpoint);
                    countDownLatch.countDown();
                });
            }
            executor.shutdown();

            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                log.error(e.getMessage(),e);
            }
        });
        logThread.shutdown();
        return null;
    }


}
